package top.go2do.common.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.go2do.common.enumeration.TokenType;

import java.util.Map;

/**
 * @Description
 * @Author xingyj
 * @CreateTime 2025/3/21 13:44
 */
@Slf4j
@Component
public class JwtUtils {

    public static final String KEY_TOKEN_TYPE = "token_type";
    public static final String KEY_EXPIRE = "expire_time";
    public static final String KEY_USER_ID = "user_id";

    @Value("${jwt.secret:0321@Lwj}")
    private String secret;

    @Value("${jwt.access-token-expiration:900000}")  // 例如 900000 (15分钟)
    private Long accessTokenExpiration;

    @Value("${jwt.refresh-token-expiration:604800000}") // 例如 604800000 (7天)
    private Long refreshTokenExpiration;
//
//    private Key getSigningKey() {
//        return Keys.hmacShaKeyFor(secret.getBytes());
//    }

    // 生成Access Token
    public String generateAccessToken(Map payload) {
        if (payload == null) {
            return "";
        }
        payload.put(KEY_TOKEN_TYPE, TokenType.ACCESS.getValue());
        payload.put(KEY_EXPIRE, System.currentTimeMillis() + accessTokenExpiration);

        return buildToken(payload);
    }

    // 生成Refresh Token
    public String generateRefreshToken(Map payload) {
        if (payload == null) {
            return "";
        }
        payload.put(KEY_TOKEN_TYPE, TokenType.REFRESH.getValue());
        payload.put(KEY_EXPIRE, System.currentTimeMillis() + refreshTokenExpiration);
        return buildToken(payload);
    }

    public String buildToken(Map payload) {
        if (payload.get(KEY_EXPIRE) == null) {
            payload.put(KEY_EXPIRE, System.currentTimeMillis() + accessTokenExpiration);
        }

        return JWTUtil.createToken(payload, secret.getBytes());
    }

    public JWT parseToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
       return jwt;
    }

    public boolean checkToken(String token) {
        Boolean result;
        try {
            result = JWTUtil.verify(token, secret.getBytes());
        } catch (JWTException jwtException) {
            log.warn("jwt check error:{}", jwtException.getMessage());
            result = false;
        } catch (Exception e) {
            log.warn("jwt check unknown error:", e);
            result = false;
        }
        return result;
    }


//    private String buildToken2(String username, Long expiration) {
//        Date now = new Date();
//        Date expiryDate = new Date(now.getTime() + expiration);
//
//        return Jwts.builder()
//                .setSubject(username)
//                .setIssuedAt(now)
//                .setExpiration(expiryDate)
//                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
//                .compact();
//    }
//
//    public Claims parseToken(String token) {
//
//        try {
//            // 解析 JWT token
//            Claims claims = Jwts.parserBuilder()
//                    .setSigningKey(getSigningKey())
//                    .build()
//                    .parseClaimsJws(token)
//                    .getBody();
//
//            // 获取 JWT 中的声明信息
//            String subject = claims.getSubject();
//            String issuer = claims.getIssuer();
//            long expiration = claims.getExpiration().getTime();
//
//            // 打印解析结果
//            System.out.println("Subject: " + subject);
//            System.out.println("Issuer: " + issuer);
//            System.out.println("Expiration: " + expiration);
//
//            // 获取自定义声明
//            String customClaim = (String) claims.get("customClaim");
//            System.out.println("Custom Claim: " + customClaim);
//
//            return claims;
//
//        } catch (Exception e) {
//            // 处理解析异常，如签名验证失败、token 过期等
//            System.out.println("Failed to parse JWT: " + e.getMessage());
//            return null;
//        }
//    }
}
